package cn.bdqn.intercepter;

import cn.bdqn.common.Result;
import cn.bdqn.common.error.LoginError;
import cn.bdqn.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

public class MyIntercepter implements HandlerInterceptor {
    private List<String> whiteList= Arrays.asList(
            "/login",
            "/"
    );
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        if(whiteList.contains(req.getServletPath())){
            return true;
        }else {
            String token = req.getHeader("Authentication");
            token="aaa";
            Object body = null;
            try {
                body = JwtUtil.parseJwt(token);
            } catch (Exception e) {
                PrintWriter out = resp.getWriter();
                Result fail = Result.fail(703, "无效TOKEN", "无效TOKEN");
                ObjectMapper mapper = new ObjectMapper();
                String s = mapper.writeValueAsString(fail);
                out.print(s);
                out.flush();
                out.close();
            }
            if(body!=null){
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("=================拦截器后置通知=================");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("=================拦截器最终通知=================");
    }
}
